package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Member;
import cn.itcast.service.MemberService;
import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    
    @Reference
    private MemberService memberService;
    
    @PostMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) throws JsonProcessingException {
        
        String  phone = (String)map.get("phone");
        String  validateCode = (String) map.get("validateCode");

        Member member= memberService.login(phone, validateCode);

        if(null==member){
            //验证码输入错误
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
      //登录成功
        /*Cookie cookie=new Cookie("login_member_telephone",phone);
        cookie.setPath("/");  //路径
        cookie.setMaxAge(60*60*30);  //有效期为1个小时
        response.addCookie(cookie);
*/
        this.redisTemplate.opsForValue().set("LOGIN_MEMBER_TELEPHONE", phone, Duration.ofMinutes(5));
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
